import base64
import uuid
from pathlib import Path


def save_base64_image(base64_str: str, save_dir: str):
    try:
        # 创建目录
        Path(save_dir).mkdir(exist_ok=True)

        # 解析 Base64
        header, data = base64_str.split(",", 1)
        file_ext = header.split("/")[1].split(";")[0]  # 如：image/png -> png

        # 生成随机文件名
        filename = f"{uuid.uuid4()}.{file_ext}"
        filepath = Path(save_dir) / filename

        # 解码并保存
        with open(filepath, "wb") as f:
            f.write(base64.b64decode(data))

        return str(filename)
    except Exception as e:
        raise ValueError(f"无效的Base64图片数据: {str(e)}")
